/*
 * @LastEditors: zhouyaxue
 * @Date: 2022-09-06 10:42:05
 * @LastEditTime: 2022-10-09 10:55:24
 */
/**
* createScript 创建script标签
* @param {string} url url链接
*/
type UseCreatedScript = (url: string) => Promise<HTMLScriptElement>
const createScript: UseCreatedScript = (url) => {
  return new Promise<HTMLScriptElement>((resolve) => {
    const script = <HTMLScriptElement>(document.createElement('script'));
    script.type = 'text/javascript';
    script.async = true;
    script.src = url;
    document.head.appendChild(script);
    script.onload = function (): void {
      resolve(script);
    };
  });
};

// 引入高德地图
type UseMapLoader = () => Promise<string>;
const MapLoader: UseMapLoader = () => {
  return new Promise<string>((resolve) => {
    if (window.AMap) {
      resolve(window.AMap);
    } else {
      createScript('https://webapi.amap.com/maps?v=2.0&key=5c2d2e1b15051cf77ecfc8740e96e0b4').then(() => {
        resolve(window.AMap);
      });
    }
  });
};

// 引入可视化高德地图
type useLocaLoader = () => Promise<string>
const LocaLoader: useLocaLoader = function () {
  return new Promise((resolve) => {
    if (window.Loca) {
      resolve(window.Loca);
    } else {
      createScript('https://webapi.amap.com/loca?v=2.0.0&key=5c2d2e1b15051cf77ecfc8740e96e0b4').then(() => {
        resolve(window.AMap);
      });
    }
  });
};
export {
  MapLoader,
  LocaLoader
};
